import 'dart:io';

import 'package:jpush_flutter/jpush_flutter.dart';
import 'package:tracker/common/log/x_logger.dart';
import 'package:tracker/common/permission/permission_manager.dart';
import 'package:tracker/startup/env/env.dart';

class JPushUtils {
  static const String appKey = '';
  static const String channel = 'theChannel';
  static bool isProduction = false;

  static JPush jpush = JPush();

  /// 初始化极光推送
  static initJPush() {
    isProduction = !Env.isTest();
    jpush.addEventHandler(
      // 接收通知回调方法。
      onReceiveNotification: (Map<String, dynamic> message) async {
        XLogger.info("jpush onReceiveNotification: $message");
      },
      // 点击通知回调方法。
      onOpenNotification: (Map<String, dynamic> message) async {
        XLogger.info("jpush onOpenNotification: $message");
        jpush.clearAllNotifications();
      },
      // 接收自定义消息回调方法。
      onReceiveMessage: (Map<String, dynamic> message) async {
        XLogger.info("jpush onReceiveMessage: $message");
      },
    );
    // 添加初始化方法，调用 setup 方法会执行两个操作：
    // 初始化 JPush SDK
    // 将缓存的事件下发到 dart 环境中。
    jpush.setup(
      appKey: appKey,
      channel: channel,
      production: isProduction,
      debug: !isProduction,
    );
    jpush.setAuth(enable: true);
  }

  /// 设置别名
  static setAlias(String alias) async {
    XLogger.info('注册推送alias: $alias');
    if (alias.isEmpty) {
      return;
    }
    final oldAliasMap = await jpush.getAlias();
    XLogger.info('oldAliasMap: $oldAliasMap');
    if (oldAliasMap.isNotEmpty && oldAliasMap['alias'] == alias) {
      return;
    }
    await jpush.deleteAlias();
    await jpush.setAlias(alias);
  }

  /// 申请安卓通知权限
  static requestAndroidPermission() {
    jpush.requestRequiredPermission();
  }

  /// 申请ios通知权限
  static requestIOSPermission() async {
    jpush.applyPushAuthority(
      const NotificationSettingsIOS(sound: true, alert: true, badge: false),
    );
  }

  static void deleteAlias() {
    jpush.deleteAlias();
  }
}
